package com.sec.android.app.myfiles.activity;

import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.Formatter;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.samsung.android.sdk.slinkcloud.CloudGatewayDeviceInfoUtils;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.util.UiUtils;

import java.lang.ref.WeakReference;

/**
 * Created by gw8951.kim on 2017-03-07.
 */

public class CloudUsageActivity extends AbsMyFilesActivity {
    protected int mProcessId;
    private Context mContext;
    private CloudMgr mCloudMgr;

    private ProgressBar mUsageProgressBar;
    private TextView mPercent;
    private TextView mPercentSign;
    private TextView mCurrentSize;
    private TextView mTotalSize;

    public static final String MYFILES_ACTION_START_CLOUD_USAGE = "com.sec.android.app.myfiles.START_SETTINGS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = this.getBaseContext();
        mCloudMgr = CloudMgr.getInstance(mContext);

        initViews();
    }

    private void initViews() {
        setContentView(R.layout.cloud_usage_layout);
        setActionBar(R.string.cloud_usage);

        UiUtils.setContentsArea(this, R.id.cloud_usage_layout_container,
                getResources().getConfiguration().screenWidthDp);

        setUsageStatusProgress();
        setDetailInfo();
    }

    public void setActionBar(int id) {
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(id);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean bRet = true;

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
                bRet = super.onOptionsItemSelected(item);
        }

        return bRet;
    }

    private BroadcastReceiver mStartCloudUsageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (MYFILES_ACTION_START_CLOUD_USAGE.equals(intent.getAction())) {
                if (getProcessId() != intent.getIntExtra(AppConstants.EXTRA_PROCESS_ID, getProcessId())) {
                    finish();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mStartCloudUsageReceiver);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.a(this, "onConfigurationChanged" + newConfig.getLayoutDirection());
        super.onConfigurationChanged(newConfig);
        UiUtils.setContentsArea(this, R.id.cloud_usage_layout_container, newConfig.screenWidthDp);
        UiUtils.setWindowAttribute(this, null);
        setDensityDpi(newConfig.densityDpi);
    }

    private void setUsageStatusProgress() {
        ViewStub cloudUsageStatusStub = (ViewStub) findViewById(R.id.cloud_usage_status_stub);
        if (cloudUsageStatusStub != null) {
            cloudUsageStatusStub.inflate();
        }
        setUsageStatus();
    }

    private void setUsageStatus() {
        String lan = getResources().getConfiguration().locale.getLanguage();
        if ("iw".equals(lan) || "ur".equals(lan) || "fa".equals(lan)) {
            mPercentSign = (TextView) findViewById(R.id.percent_sign_for_hebrew);
        } else {
            mPercentSign = (TextView) findViewById(R.id.percent_sign);
        }

        mPercent = (TextView) findViewById(R.id.percent);
        mCurrentSize = (TextView) findViewById(R.id.current_size);
        mTotalSize = (TextView) findViewById(R.id.total_size);
        mUsageProgressBar = (ProgressBar) findViewById(R.id.progress_bar);

        StorageThread thread = new StorageThread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private void setDetailInfo() {
        View container;
        ViewStub stub = (ViewStub) findViewById(R.id.cloud_detail_info_stub);
        if (stub != null) {
            container = stub.inflate();
        } else {
            container = findViewById(R.id.cloud_detail_info);
        }
        long[] detailedUsed = getCloudCategorySize(CloudGatewayDeviceInfoUtils.GET_STORAGE_USED);
        if (container != null && detailedUsed != null && detailedUsed.length != 0) {
            setInfoItemList(container.findViewById(R.id.google_drive_usage_info), getString(R.string.google_drive),
                    Formatter.formatFileSize(mContext, detailedUsed[0]));
            setInfoItemList(container.findViewById(R.id.gmail_usage_info), getString(R.string.gmail),
                    Formatter.formatFileSize(mContext, detailedUsed[1]));
            setInfoItemList(container.findViewById(R.id.google_photo_usage_info), getString(R.string.google_photo),
                    Formatter.formatFileSize(mContext, detailedUsed[2]));
        }
    }

    private long[] getCloudCategorySize(String strInfoType) {
        long[] bRet = new long[3];
        Bundle resultBundle = CloudGatewayDeviceInfoUtils.getInstance(mContext).
                getVersatileInformation(strInfoType,
                        mCloudMgr.getDeviceId(FileRecord.CloudType.GoogleDrive));
        if (resultBundle != null) {
            return resultBundle.getLongArray("result");
        }
        return bRet;
    }

    private void setInfoItemList(View view, String title, String size) {
        if (view != null) {
            TextView mainText = (TextView) view.findViewById(R.id.cloud_detail_info_list_item_text);
            if (mainText != null) {
                mainText.setText(title);
                mainText.setVisibility(View.VISIBLE);
            }
            TextView sizeText = (TextView) view.findViewById(R.id.cloud_detail_info_list_item_text_second);
            if (sizeText != null) {
                sizeText.setText(size);
                sizeText.setVisibility(View.VISIBLE);
            }
        }
    }

    static void setViewInfo(TextView currentSizeView, TextView totalSizeView, String info) {
        if (info != null) {
            int index = info.lastIndexOf('/');
            String currentSize = info.substring(0, index);
            String totalSize = info.substring(index);
            currentSizeView.setText(currentSize);
            currentSizeView.setVisibility(View.VISIBLE);
            totalSizeView.setText(totalSize);
            totalSizeView.setVisibility(View.VISIBLE);
        } else {
            currentSizeView.setVisibility(View.GONE);
            totalSizeView.setVisibility(View.GONE);
        }
    }

    private final Handler mStorageHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                setViewInfo(mCurrentSize, mTotalSize, (String) msg.obj);
                int percent = msg.arg1;
                mUsageProgressBar.setProgress(percent);
                mPercent.setText(String.valueOf(percent));
                mPercentSign.setText("%");
            }
        }
    };

    private static class StorageThread extends Thread {
        private Context mContext;
        private CloudMgr mCloudMgr;
        private WeakReference<CloudUsageActivity> mActivityWeak;

        private StorageThread(CloudUsageActivity activity) {
            mContext = activity.getApplicationContext();
            mCloudMgr = activity.mCloudMgr;
            mActivityWeak = new WeakReference<>(activity);
        }

        @Override
        public void run() {
            long newUsedSize = 0;
            long totalSize = 0;
            long[] quota = UiUtils.updateQuota(mContext, mCloudMgr, FileRecord.CloudType.GoogleDrive);

            if (quota != null && quota.length != 0) {
                totalSize = quota[0];
                newUsedSize = quota[1];
            }

            if (totalSize != 0) {
                ensureSizeView(totalSize, newUsedSize);
            }
        }

        private void ensureSizeView(long totalSize, long usedSize) {
            Message msg = Message.obtain();
            msg.what = 0;
            msg.obj = Formatter.formatFileSize(mContext, usedSize) + " / " +
                    Formatter.formatFileSize(mContext, totalSize);
            msg.arg1 = (int) (usedSize * 100 / totalSize);
            CloudUsageActivity activity = mActivityWeak.get();
            if (activity != null) {
                activity.mStorageHandler.sendMessage(msg);
            }
        }
    }
}
